package com.sinoglobal.ningxia.activity.player;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.sinoglobal.dumping.util.PicassoCircleImageTransFormat;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.adapter.VideoPlayerCommentAdapter;
import com.sinoglobal.ningxia.beans.BaseBean;
import com.sinoglobal.ningxia.beans.CommentBean;
import com.sinoglobal.ningxia.beans.CommentSubmitVo;
import com.sinoglobal.ningxia.beans.LiveHomeBean;
import com.sinoglobal.ningxia.beans.LookNumBean;
import com.sinoglobal.ningxia.dialog.CommentDialog;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.StringUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.TimeUtil;
import com.sinoglobal.ningxia.utils.ToastBuilder;
import com.sinoglobal.ningxia.view.InnerListView;
import com.sinoglobal.ningxia.view.ScrollBottomScrollView;
import com.squareup.picasso.Picasso;

import net.tsz.afinal.FinalBitmap;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * Created by XINDZ on 2017/2/13.
 * 功能: 视频播放的activity
 */

public class VideoPlayerActivity extends ShareAbstractActivity {
    private String VideoUrl = "http://2449.vod.myqcloud.com/2449_43b6f696980311e59ed467f22794e792.f20.mp4";
    private RelativeLayout rlVideoplayviewTitle;
    private LinearLayout titleBack;
    private TextView tvTitleName;
    private ImageView ivLogo;
    private TextView tvLookNum;
    private TextView tvCommentNum;
    private TextView tvShare;
    private LinearLayout llIntro;
    private TextView tvIntro;
    private ImageView ivMyHeadicon;
    private TextView tvSendComment;
    private TextView tvNoComment;
    private InnerListView ilvComment;
    private CommentDialog commentDialog;
    private ImageView ivPop;
    private LiveHomeBean.ListBean dataBean;
    /**
     * 图片加载工具类
     */
    private FinalBitmap fb;
    /**
     * 默认头像
     */
    private Bitmap defaultPic;
    private List<CommentBean.ListBean> commmentList = new ArrayList();
    private VideoPlayerCommentAdapter commentAdapter;
    private ScrollBottomScrollView sbvView;
    private int liveID;//直播ID
    private int pageNo = 0;//直播ID
    private String liveUrl;
    private String liveImg;
    private String liveTitle;
    private String liveIntro;
    private int liveSums;

    private String testIntro = "信诺红枸杞测试简介（摘要）<span style=\\\"line-height:28px;\\\">信息</span>";
    private String liveLogo;
    private JCVideoPlayerStandard jcVideoPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videoplayer);
        titleView.setText(getString(R.string.app_name));
        dataBean = (LiveHomeBean.ListBean) getIntent().getSerializableExtra(LiveHomeBean.class.getCanonicalName());
        if (dataBean != null) {
            liveID = dataBean.getId();
            liveUrl = dataBean.getUrl();
            liveImg = dataBean.getImg();
            liveTitle = dataBean.getTitle();
            liveIntro = dataBean.getIntro();
            if (liveIntro == null) {
                liveIntro = "";
            }
            liveSums = dataBean.getSums();
            liveLogo = dataBean.getLogo();
            titleView.setText(liveTitle);
        }
        initView();
        initDialog();
        initListener();
        openChenJInShi();
//        jcVideoPlayer.setUp("http://58.221.254.33:1935/live/zhongwen.sdp/playlist.m3u8", JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL);
        jcVideoPlayer.setUp(liveUrl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL);
        if (liveImg != null && !liveImg.equals("")) {
            Picasso.with(this).load(liveImg)
                    .into(jcVideoPlayer.thumbImageView);
            jcVideoPlayer.thumbImageView.setScaleType(ImageView.ScaleType.FIT_XY);
        }
        jcVideoPlayer.backButton.setVisibility(View.GONE);
        jcVideoPlayer.tinyBackImageView.setVisibility(View.GONE);
//        jcVideoPlayer.bottomProgressBar.set
        RemoteImpl.getInstance().getNewslookNum(this, liveID + "", 3).execute(new ResultCallback(this));
        RemoteImpl.getInstance().getLookNum(this, liveID + "", 3).execute(new ResultCallback(this) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                LookNumBean lookNumBean = JSONObject.parseObject(response, LookNumBean.class);
                if (lookNumBean != null && lookNumBean.getCode() == 0) {
                    tvLookNum.setText("播放" + lookNumBean.getSums() + "次");
                }
            }
        });
    }


    private void initView() {
        //播放器
        jcVideoPlayer = (JCVideoPlayerStandard) findViewById(R.id.jc_player_videoplayer);
        //Pop参照view
        ivPop = (ImageView) findViewById(R.id.iv_pratline);

        //Logo 播放次数 评论数 分享
        ivLogo = (ImageView) findViewById(R.id.iv_videoplayer_logo);
        tvLookNum = (TextView) findViewById(R.id.tv_videoplayview_looknum);
        tvCommentNum = (TextView) findViewById(R.id.tv_videoplayview_commentnum);
        tvShare = (TextView) findViewById(R.id.tv_videoplayview_share);
        tvLookNum.setText("播放" + liveSums + "次");


        //简介
        llIntro = (LinearLayout) findViewById(R.id.ll_videoplayer_intro);
        tvIntro = (TextView) findViewById(R.id.tv_videoplayview_intro);
        if (liveIntro != null) {
            tvIntro.setText(Html.fromHtml(liveIntro));
        }

        //评论
        sbvView = (ScrollBottomScrollView) findViewById(R.id.sbv_videoplayview);
        ivMyHeadicon = (ImageView) findViewById(R.id.iv_videoplayer_myheadicon);
        tvSendComment = (TextView) findViewById(R.id.tv_videoplayview_sendcomment);
        tvNoComment = (TextView) findViewById(R.id.tv_videoplayview_noComment);
        ilvComment = (InnerListView) findViewById(R.id.ilv_videoplayer_comment);
        //设置LOGO
        if (liveLogo != null && !liveLogo.equals("")) {
            Picasso.with(this).load(liveLogo)
                    .placeholder(R.drawable.ningxia_logo)
                    .error(R.drawable.ningxia_logo)
                    .into(ivLogo);
        }

        //设置头像
        defaultPic = BitmapFactory.decodeResource(
                FlyApplication.context.getResources(), R.drawable.icon_my_defaulthead);
        if (FlyApplication.isShowPic
                && !StringUtil.isNullOrEmpty(SharedPreferenceUtil.getString(FlyApplication.context, "photo"))) {
            Picasso.with(this).load(SharedPreferenceUtil.getString(FlyApplication.context, "photo"))
                    .transform(new PicassoCircleImageTransFormat())
                    .placeholder(R.drawable.personal_list_portrait)
                    .error(R.drawable.personal_list_portrait)
                    .into(ivMyHeadicon);
        } else {
            ivMyHeadicon.setImageResource(R.drawable.personal_list_portrait);
        }
        //滑动到底部监听
        sbvView.setScrollBottomListener(new ScrollBottomScrollView.ScrollBottomListener() {
            @Override
            public void scrollBottom() {
                loadData();
            }
        });
        loadData();
        sbvView.smoothScrollTo(0, 0);
    }

    private void loadData() {
        ResultCallback liveComtListCallBack = new ResultCallback(this) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                CommentBean commentBean = JSONObject.parseObject(response, CommentBean.class);
                if (commentBean.getCode() == 0) {
                    List<CommentBean.ListBean> commentBeanList = commentBean.getList();
                    if (commentBeanList != null && commentBeanList.size() > 0) {
                        tvNoComment.setVisibility(View.GONE);
                    }
                    commmentList = commentBeanList;
                    //初始化Adapter
                    initAdapter();
                }
            }
        };
        RemoteImpl.getInstance().getLiveCommentList(this, liveID + "", pageNo, 10).execute(liveComtListCallBack);
    }

    private void initAdapter() {
        if (commentAdapter == null) {
            commentAdapter = new VideoPlayerCommentAdapter(this, commmentList);
        }
        ilvComment.setAdapter(commentAdapter);
        commentAdapter.setCommentList(commmentList);
        commentAdapter.notifyDataSetChanged();
    }

    private void initDialog() {
        commentDialog = new CommentDialog(this);
        commentDialog.setAddComment(new CommentDialog.AddComment() {
            @Override
            public void onAddComment(final String str) {
                //TODO 目前没有直播ID要更换直播ID
                if (TextUtil.stringIsNotNull(FlyApplication.userId)) {// 已登录
                    Logger.i("用户的头像URL:" + SharedPreferenceUtil.getString(FlyApplication.context, "photo"));
                    RemoteImpl.getInstance().submitLiveComment(VideoPlayerActivity.this,
                            new CommentSubmitVo(1, str, liveID + "", "4"), VideoPlayerActivity.this)
                            .execute(new ResultCallback(VideoPlayerActivity.this) {
                                @Override
                                public void onSuccess(String response) {
                                    super.onSuccess(response);
                                    BaseBean baseBean = JSON.parseObject(response, BaseBean.class);
                                    if (baseBean != null) {
                                        int code = baseBean.getCode();
                                        String message = baseBean.getMessage();
                                        if (code == 0) {
                                            CommentBean.ListBean sendlistBean = new CommentBean.ListBean();
                                            sendlistBean.setContent(str);
                                            sendlistBean.setNickname(SharedPreferenceUtil.getString(VideoPlayerActivity.this, "nickname"));
                                            sendlistBean.setCreate_time(TimeUtil.getLongPointDate(System.currentTimeMillis()));
                                            sendlistBean.setUser_img(SharedPreferenceUtil.getString(FlyApplication.context, "photo"));
                                            commmentList.add(0, sendlistBean);
                                            initAdapter();
                                            ToastBuilder.getIntance(FlyApplication.context).showToast(message);
                                        }
                                    }
                                }
                            });
                } else {
                    FlyUtil.intentForward(VideoPlayerActivity.this, Login.class);
                }


            }
        });
    }

    /**
     * 简介的Pop
     */
    private void showIntroPopwindow() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.pop_videoplay_intro,
                null);
        TextView tvPopIntro = (TextView) view
                .findViewById(R.id.tv_pop_intro);
        tvPopIntro.setText(Html.fromHtml(liveIntro));
        LinearLayout llPopClose = (LinearLayout) view.findViewById(R.id.ll_pop_close);

        final PopupWindow window = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.PoP_anim_style);
        // 在参照的View控件下方显示
        window.showAsDropDown(ivPop, 0, 0);

        llPopClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                window.dismiss();

            }
        });
    }

    private void initListener() {

        //分享
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopwindow(true, "我正在使用#红枸杞#手机客户端，里面有很多精彩的内容.更多 > http://nxtv.sinosns.cn", null, "http://nxtv.sinosns.cn/");
            }
        });
        //简介
        llIntro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showIntroPopwindow();
            }
        });
        //评论
        tvSendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentDialog.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }


}
